/*
 * @Description:
 * @Author: baimenghan
 * @Email: baimenghan@nnuo.com
 * @Date: 2022-02-28 11:14:21
 * @LastEditors: baimenghan
 * @LastEditTime: 2022-02-28 20:00:08
 * @FilePath: \daka\src\components\FormDialog\FormDialog.jsx
 */
import "./FormDialog.sass";
import React, { useEffect, useState } from "react";
import { Form, Input, Button, InputNumber } from "antd";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import emitter from "@/services/event";
import { useNavigate } from "react-router-dom";
import { updateConfigApi } from "@/api/configApi";
import { chineseTransform } from "@/utils/common";

const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};

const FormDialog = (props) => {
  // 生成表单实例
  const [form] = Form.useForm();
  let navigate = useNavigate();
  // const history = createHistory();
  // 点击提交按钮后，values 为数组值
  const onFinish = (values) => {
    emitter.emit("refresh", values.names);
    values = formOrInput
      ? JSON.stringify(values.names)
      : JSON.stringify(values.names[0]);
    updateConfigApi({ configName, configValue: values });
    closeDialog();
    window.location.reload();
  };

  const [isDisplay, setIsDisplay] = useState(false);
  const [configName, setConfigName] = useState("");
  const [configValue, setConfigValue] = useState([]);
  // formOrInput 为 true 展示列表弹框，为 false 展示数字输入框弹框
  const [formOrInput, setFormOrInput] = useState(true);
  // 当点击编辑按钮后，通过 isDisplay 的值来决定是否弹框
  useEffect(() => {
    emitter.addListener(
      "openDialog",
      (isShow, configName, configValue, formOrInput) => {
        setIsDisplay(isShow);
        setConfigName(configName);
        formOrInput
          ? (configValue = JSON.parse(configValue))
          : (configValue = [configValue]);
        setConfigValue(configValue);
        form.setFieldsValue({ names: configValue });
        setFormOrInput(formOrInput);
      }
    );
  }, [form]);

  // 关闭弹窗
  const closeDialog = () => {
    setIsDisplay(false);
  };

  return (
    <div
      className={false || isDisplay ? "dialog-box-show" : "dialog-box-hidden"}
    >
      <Form
        form={form}
        className="form-box"
        name="dynamic_form_item"
        {...formItemLayoutWithOutLabel}
        onFinish={onFinish}
        initialValues={{ names: configValue }}
      >
        <Form.List name="names">
          {(fields, { add, remove }, { errors }) => (
            <>
              <Form.Item>
                <h1 className="form-title">{chineseTransform(configName)}</h1>
              </Form.Item>
              {/* field 即每一行区域 */}
              {fields.map((field, index) => {
                return formOrInput ? (
                  <Form.Item
                    {...formItemLayoutWithOutLabel}
                    required={false}
                    key={field.key}
                  >
                    <Form.Item
                      {...field}
                      validateTrigger={["onChange", "onBlur"]}
                      rules={[
                        {
                          required: true,
                          whitespace: true,
                          message: "内容不能为空",
                        },
                      ]}
                      noStyle
                    >
                      <Input
                        placeholder="请输入内容"
                        style={{ width: "60%" }}
                      />
                    </Form.Item>
                    {fields.length > 1 ? (
                      <MinusCircleOutlined
                        className="delete-btn"
                        onClick={() => remove(field.name)}
                      />
                    ) : null}
                  </Form.Item>
                ) : (
                  <Form.Item {...field}>
                    <InputNumber
                      className="input-number"
                      min={3600}
                      max={600000000}
                    />
                  </Form.Item>
                );
              })}
              {formOrInput ? (
                <Form.Item>
                  <Button
                    type="dashed"
                    onClick={() => add()}
                    style={{ width: "60%", color: "#917f41" }}
                    icon={<PlusOutlined />}
                  >
                    新增一项
                  </Button>
                  <Form.ErrorList errors={errors} />
                </Form.Item>
              ) : null}
            </>
          )}
        </Form.List>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
          <Button className="btn-margin" type="danger" onClick={closeDialog}>
            取消
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default FormDialog;
